<template>
	<div class="user-select">
		<slot :open="onOpenDialog">
			<el-input :value="selectName" readonly @click.native="onOpenDialog" :placeholder="placeholder"></el-input>
		</slot>

		<el-dialog :visible.sync="visible" title="选择会员/组" modal-append-to-body append-to-body lock-scroll width="1000px">
			<el-card shadow="never">
				<el-row>
					<el-col class="v-col left" :span="12">
						<el-row :gutter="6">
							<el-col :span="20">
								<el-input v-model="keyword" clearable placeholder="请输入内容" prefix-icon="el-icon-search" @input="onKeywordChange"></el-input>
							</el-col>
							<el-col :span="4">
								<el-button style="width: 100%" plant icon="el-icon-search" @click="onKeywordChange"></el-button>
							</el-col>
						</el-row>
						<el-tabs v-model="active">
							<el-tab-pane name="group" label="会员组" v-if="!noGroup">
								<div class="item no-hover" @click="isGroupCheckAll = !isGroupCheckAll">
									<el-checkbox class="el-checkbox" v-model="isGroupCheckAll"></el-checkbox>
									<span>全选</span>
								</div>
								<div class="item" v-for="item in filterGroupList" :key="item.id" @click="onGroupChange(item)">
									<el-checkbox class="el-checkbox" :value="selectIds.includes(item.id)"></el-checkbox>
									<img src="@/assets/dept-logo.svg" alt="logo" />
									<span>{{ item.name }}</span>
								</div>
							</el-tab-pane>
							<el-tab-pane name="member" label="会员" v-if="!noMember">
								<div class="item no-hover" @click="isMemberCheckAll = !isMemberCheckAll">
									<el-checkbox class="el-checkbox" v-model="isMemberCheckAll"></el-checkbox>
									<span>全选</span>
								</div>
								<div class="item" v-for="item in memberList" :key="item.id" @click="onMemberChange(item)">
									<el-checkbox class="el-checkbox" :value="selectIds.includes(item.id)"></el-checkbox>
									<div class="avatar" v-if="item.avatar">
										<img :src="item.avatar" alt="avatar" />
									</div>
									<div class="avatar" v-else>{{ item.nickName.slice(0, 2) }}</div>
									<span>{{ item.nickName }}</span>
								</div>

								<el-pagination class="el-pagination" background layout="prev, pager, next" :current-page.sync="member.current" :total="+member.total" @current-change="onPageChange" hide-on-single-page></el-pagination>
							</el-tab-pane>
						</el-tabs>
					</el-col>
					<el-col class="v-col right" :span="12">
						<div class="tip">
							共
							<span>{{ groupSelect.length + memberSelect.length }}</span>
							个, 其中
							<span>{{ groupSelect.length }}</span>
							个会员组,
							<span>{{ memberSelect.length }}</span>
							个会员

							<el-button
								type="primary"
								icon="el-icon-delete"
								size="mini"
								class="el-button"
								@click="
									groupSelect = []
									memberSelect = []
								"
							>
								清空
							</el-button>
						</div>
						<div class="right-main">
							<div class="item" v-for="(item, index) in groupSelect" :key="item.id">
								<img src="@/assets/dept-logo.svg" alt="logo" />
								<span>{{ item.name }}</span>
								<el-button class="el-button" type="text" icon="el-icon-close" @click="onGroupDelete(index)"></el-button>
							</div>
							<div class="item" v-for="(item, index) in memberSelect" :key="item.id">
								<div class="avatar" v-if="item.avatar">
									<img :src="item.avatar" alt="avatar" />
								</div>
								<div class="avatar" v-else>{{ item.nickName.slice(0, 2) }}</div>
								<span>{{ item.nickName }}</span>
								<el-button class="el-button" type="text" icon="el-icon-close" @click="onMemberDelete(index)"></el-button>
							</div>
						</div>
					</el-col>
				</el-row>
			</el-card>

			<template #footer>
				<el-button type="danger" @click="onCancel">取 消</el-button>
				<el-button type="success" @click="onConfirm">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import request from "@/common/request"

let timer = null

export default {
	name: "user-select",
	model: {
		prop: "value",
		event: "update:value",
	},
	props: {
		placeholder: {
			type: String,
			default: "选择会员",
		},
		value: {
			type: Object,
			default: () => ({
				userGroup: [],
				member: [],
			}),
		},
		noGroup: {
			type: Boolean,
			default: false,
		},
		noMember: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			visible: false,
			type: "group",
			keyword: "",

			groupList: [],
			memberList: [],
			member: {
				current: 1,
				total: 0,
				size: 10,
			},

			groupSelect: [],
			memberSelect: [],
		}
	},
	computed: {
		active: {
			get() {
				if (this.noGroup) {
					return "member"
				}
				if (this.noMember) {
					return "group"
				}
				return this.type
			},
			set(val) {
				if (this.noGroup || this.noMember) return
				this.type = val
			},
		},

		filterGroupList() {
			return this.groupList.filter(item => item.name.includes(this.keyword))
		},

		isGroupCheckAll: {
			get() {
				if (this.filterGroupList.length == 0) return false
				return this.filterGroupList.every(item => this.selectIds.includes(item.id))
			},
			set(val) {
				if (val) {
					this.filterGroupList.forEach(item => {
						if (!this.selectIds.includes(item.id)) {
							this.groupSelect.push(item)
						}
					})
				} else {
					this.groupSelect = this.groupSelect.filter(item => !this.selectIds.includes(item.id))
				}
			},
		},
		isMemberCheckAll: {
			get() {
				if (this.memberList.length == 0) return false
				return this.memberList.every(item => this.selectIds.includes(item.id))
			},
			set(val) {
				if (val) {
					this.memberList.forEach(item => {
						if (!this.selectIds.includes(item.id)) {
							this.memberSelect.push(item)
						}
					})
				} else {
					this.memberSelect = this.memberSelect.filter(item => !this.selectIds.includes(item.id))
				}
			},
		},

		selectName() {
			const { userGroup, member } = this.value

			let groupNames = ""
			let memberNames = ""
			if (userGroup && userGroup.length > 0) {
				groupNames = userGroup.map(item => item.name).join(",")
			}
			if (member && member.length > 0) {
				memberNames = member.map(item => item.nickName).join(",")
			}
			return `${groupNames}${groupNames && memberNames ? "," : ""}${memberNames}`
		},
		selectIds() {
			let groupIds = []
			let memberIds = []
			if (this.groupSelect.length > 0) {
				groupIds = this.groupSelect.map(item => item.id)
			}
			if (this.memberSelect.length > 0) {
				memberIds = this.memberSelect.map(item => item.id)
			}
			return [...groupIds, ...memberIds]
		},
	},
	created() {
		if (!this.noGroup) {
			this.getMemberGroup()
		}
	},
	methods: {
		onOpenDialog() {
			this.active = "group"

			this.groupSelect = [].concat(this.value.userGroup || [])
			this.memberSelect = [].concat(this.value.member || [])

			this.keyword = ""
			this.member.current = 1
			this.getMember()

			this.visible = true
		},
		onGroupChange(item) {
			const index = this.groupSelect.findIndex(i => i.id == item.id)
			if (index > -1) {
				this.groupSelect.splice(index, 1)
			} else {
				this.groupSelect.push(item)
			}
		},
		onGroupDelete(index) {
			this.groupSelect.splice(index, 1)
		},
		onMemberChange(item) {
			const index = this.memberSelect.findIndex(i => i.id == item.id)
			if (index > -1) {
				this.memberSelect.splice(index, 1)
			} else {
				this.memberSelect.push(item)
			}
		},
		onMemberDelete(index) {
			this.memberSelect.splice(index, 1)
		},

		async getMemberGroup() {
			try {
				const { code, data, msg } = await request("get", "/member/memberGroup/list")
				if (code != 0) {
					throw new Error(msg)
				}
				this.groupList = data
			} catch (error) {
				this.$message.error(error.message)
			}
		},
		async getMember() {
			try {
				const {
					code,
					msg,
					data: { records, total },
				} = await request("get", "/member/member/page", {
					current: this.member.current,
					size: this.member.size,
					nickName: this.keyword,
				})
				if (code != 0) {
					throw new Error(msg)
				}
				this.memberList = records
				this.member.total = total
			} catch (error) {
				this.$message.error(error.message)
			}
		},
		onPageChange(current) {
			this.member.current = current
			this.getMember()
		},

		onKeywordChange() {
			console.log(1)
			clearTimeout(timer)
			timer = setTimeout(() => {
				console.log(2)
				if (this.active == "member") {
					this.member.current = 1
					this.getMember()
				}
			}, 500)
		},

		onCancel() {
			this.visible = false
		},
		onConfirm() {
			this.$emit("update:value", {
				userGroup: [].concat(this.groupSelect),
				member: [].concat(this.memberSelect),
			})
			this.$emit("change", {
				userGroup: [].concat(this.groupSelect),
				member: [].concat(this.memberSelect),
			})
			this.visible = false
		},
	},
}
</script>

<style lang="scss" scoped>
.v-col {
	height: 640px;
	overflow-y: auto;
	&.left {
		padding-right: 20px;
	}
	&.right {
		border-left: 1px solid #f5f5f5;
		padding-left: 20px;
		position: relative;
		padding-top: 40px;
		.right-main {
			width: 100%;
			height: 100%;
			overflow-y: auto;
		}
	}
}

.tip {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding-bottom: 10px;
	background: #fff;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	padding-left: 20px;
	span {
		margin-inline: 5px;
		color: #409eff;
	}
	.el-button {
		margin-left: auto;
	}
}

.item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-block: 7px;
	padding-inline: 10px;
	gap: 7px;
	cursor: pointer;
	border-radius: 5px;
	margin-bottom: 1px;
	transition: all 0.2s;

	&:hover {
		background-color: #f5f5f5;
		&.no-hover {
			background: #fff;
		}
	}
	.el-checkbox {
		pointer-events: none;
		flex: none;
	}
	img {
		width: 30px;
		height: 30px;
		flex: none;
	}
	.avatar {
		width: 30px;
		height: 30px;
		flex: none;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		font-size: 12px;
		color: #fff;
		background: #0cafcc;

		img {
			width: 100%;
			aspect-ratio: 1 / 1;
			object-fit: cover;
			border-radius: 50%;
			display: block;
		}
	}
	span {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.el-button {
		flex: none;
		padding: 0;
	}

	/deep/ label {
		margin-bottom: 0;
	}
}
.el-pagination {
	margin-top: 20px;
}

.el-pagination /deep/ .el-pagination.is-background .el-pager li:not(.disabled).active {
	background-color: #0cafcc;
	color: #fff;
}
.el-pagination /deep/ .el-pager li.active {
	color: #fff !important;
}
</style>
